package com.example.recycler_view;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
                                    //继承recyclerView的适配器
public class Recycler_Adapter extends RecyclerView.Adapter<Recycler_Adapter.MyHolder> {
        private List<mode> mlist;   //创建list对象
        //使用构造方法初始化list
        public Recycler_Adapter(List<mode> list) {
            mlist = list;
        }

        /**
        * 用于创建ViewHolder实例,并把加载的布局传入到构造函数去,
         * 再把ViewHolder实例返回。
         */
    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.mode_view,parent,false);
        final MyHolder holder=new MyHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int p=holder.getAdapterPosition();
                mode mode = mlist.get(p);
                Toast.makeText(view.getContext(), "你点击了："+mode.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

      /**
       * 用于对子项的数据进行赋值,会在每个子项被滚动到屏幕内时执行
       * position得到当前项的mode实例。
      */
    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        mode mode=mlist.get(position);
        holder.img.setImageResource(mode.getImg());
        holder.title.setText(mode.getTitle());
        holder.nr.setText(mode.getNr());
    }

    /**
     *  getItemCount()返回RecyclerView的子项数目。
    */
    @Override
    public int getItemCount() {
        return mlist.size();
    }

    class MyHolder extends RecyclerView.ViewHolder{
        ImageView img;
        TextView title;
        TextView nr;
        public MyHolder(View v) {
            super(v);
            img=v.findViewById(R.id.image);
            title=v.findViewById(R.id.title);
            nr=v.findViewById(R.id.nr);
        }
    }
}
